package firstServlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletContext;

public class Util {

	private static String startPrefix = "-----------------------------";
	private static String endPrefix = "--";
	private static String filename = "filename";

	public static void upload(InputStream stream, ServletContext context)
			throws IOException {

		BufferedReader reader = new BufferedReader(
				new InputStreamReader(stream));
		String temp;
		while ((temp = reader.readLine()) != null) {
			System.out.println(temp);
			if (temp.startsWith(startPrefix) && temp.endsWith(endPrefix)) {
				break;
			}
			if (temp.startsWith(startPrefix)) {
				temp = reader.readLine();
				if (temp != null) {
					int len = temp.indexOf(filename);
					
					if (len > 1) {
						reader.readLine();
						reader.readLine();
						String localName = getFileName(temp, len);
						File file = new File(context.getRealPath("/")
								+ localName + System.currentTimeMillis());
						System.out.println(context.getRealPath("/"));
						FileWriter writer = new FileWriter(file);

						while ((temp = reader.readLine()) != null) {
							if (temp.startsWith(startPrefix)) {
								writer.flush();
								writer.close();
								
								
							}
							writer.append(temp);
						}
						writer.flush();
						writer.close();
					}
				}
			}
		}
		reader.close();
	}

	private static String getFileName(String str, int len) {
		int strlen = str.length();
		String result = str.substring(len + filename.length() + 2, strlen - 1);
		int ll=result.lastIndexOf(".");
		if(ll>0){
			result=result.substring(0, ll);
		}
		return result;
	}
//	private static void get(){
//		String str="aa.aa";
//		int len=str.lastIndexOf(".");
//		System.out.println(len);
//	}
	public static void main(String[] args) {
		String str="Content-Disposition: form-data; name=\"file1\"; filename=\"HelloWorld.java\"";
		int len=str.indexOf(filename);
		String result=getFileName(str, len);
		System.out.println(result);
		
//		get();
	}

}
